<template>
  <div id="account_trade">
    <el-form
      ref="ruleForm"
      :model="order"
      status-icon
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="收款学生" prop="toId">
        <el-select
          v-model="order.toId"
          filterable
          remote
          @change="setToName"
          loading-text="正在搜索..."
          placeholder="请输入学号搜索"
          :remote-method="remoteMethod"
          :loading="false"
        >
          <el-option
            :label="student.studentName"
            :key="student._id"
            v-for="student in students"
            :value="student._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 这里就省事 写死了两种类型哦 -->
      <el-form-item label="交易类型" prop="tradeType">
        <el-select v-model="order.tradeType" placeholder="请选择交易类型">
          <el-option label="转账" value="0"></el-option>
          <el-option label="其他费用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="交易描述" prop="tradeDesc">
        <el-input v-model="order.tradeDesc" placeholder="请输入描述"></el-input>
      </el-form-item>
      <el-form-item label="交易金额" prop="tradeMoney">
        <el-input
          type="number"
          v-model="order.tradeMoney"
          placeholder="请输入金额"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="交易日期" prop="tradeCreateDate">
        <el-input
          v-model="order.tradeCreateDate"
          placeholder="请选择交易日期"
        ></el-input>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >创建订单并扫码支付</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
import rules from "../commons/validate";
import qrcode from "qrcode";
import { isMobile } from "@/util/util";

import {
  useFindStudentByStudentNo,
  useGetOrder,
  useAddOrder,
} from "@/hooks/order";

import { payApi } from "@/api/api_constant";

import { mapState } from "vuex";

import config from "@/config";

export default {
  name: "AccountTrade",
  data() {
    return {
      rules,
      students: [],
      order: {
        orderNo: nanoid(),
        toId: "",
        toName: "",
        fromId: "",
        fromName: "",
        tradeType: "",
        tradeDesc: "",
        tradeMoney: "",
        tradeCreateDate: "",
      },
    };
  },

  computed: {
    ...mapState("user", ["userInfo"]),
  },

  mounted() {},

  sockets: {
    connect: function () {
      console.log("链接pay socket服务器........");
    },
    disconnect() {
      console.log("断开socket服务器连接");
    },
    pay: function (status) {
      if (status === 1) {
        this.$message({
          type: "error",
          message: "订单过期",
        });
        setTimeout(() => {
          location.href = "http://192.168.0.105:8080/account/spend";
        }, 1000);
      } else if (status === 2) {
        this.$message({
          type: "success",
          message: "订单交易成功",
        });
        setTimeout(() => {
          location.href = "http://192.168.0.105:8080/account/spend";
        }, 1000);
      } else {
        this.$message({
          type: "error",
          message: "订单交易失败",
        });
      }
    },
  },

  methods: {
    setToName(sid) {
      const stu = this.students.filter((c) => {
        return sid === c._id;
      })[0];
      this.order.toName = stu.studentName;
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const return_url = "http://192.168.0.105:3000/api/pay/return_url";
          const notify_url = "http://192.168.0.105:3000/api/pay/notify_url";
          this.order.fromName =
          this.userInfo.studentName || this.userInfo.teacherName;
          this.order.fromId = this.userInfo._id;
          this.order.tradeCreateDate = new Date().getTime();
          const orderNo = (await useAddOrder(this.order)).data?.orderNo;
          this.order.orderNo = nanoid();
          if (!isMobile()) {
            // 生成订单 生成二维码 - 移动端无需生成二维码直接携带订单号跳转到后台地址返回支付页面
            //  未扫码就点击我已支付 查询订单支付状态 作出反馈
            // 二维码有效时间1分钟 超过当前订单过期 支付页面提示订单过期 并跳转到支付失败界面
            // 生成二维码并携带订单号 扫码跳转到后台 后台返回支付界面 - 不可在前端做这一步
            // 支付界面点击确认支付
            // 支付成功 跳转到支付成功界面 PC 界面做出相应反馈
            // 后台修改订单状态为已支付 并通知前端
            const h = this.$createElement;
            this.$msgbox({
              title: "扫码支付",
              center: true,
              dangerouslyUseHTMLString: true,
              message: `<div style="width:168px;height:168px;position:relative;margin:0 auto"> <img width="168" height="168" src="${await qrcode.toDataURL(
                `${config.baseURL}${payApi}?orderNo=${orderNo}&return_url=${return_url}&notify_url=${notify_url}`,
                {
                  errorCorrectionLevel: "H",
                  type: "image/jpeg",
                  quality: 0.3,
                  margin: 1,
                }
              )}"/> <div style="position:absolute;left:50%;top:50%;width:50px;height:50px;background:white;line-height:80px;text-align:center;transform:translate(-50%,-50%)"><img width="40" height="40" src="${this.userInfo.studentAvatar || this.userInfo.teacherAvatar}" ></div></div>`,
              showCancelButton: true,
              confirmButtonText: "我已完成支付",
              cancelButtonText: "取消",
              beforeClose: async (action, instance, done) => {
                if (action === "confirm") {
                  instance.confirmButtonLoading = true;
                  instance.confirmButtonText = "获取支付结果中...";
                  const order = (await useGetOrder(orderNo)).data?.order[0];
                  if (order.tradePayStatus === 0) {
                     this.$message.error("还未完成支付")
                     instance.confirmButtonText = "我已完成支付";
                     instance.confirmButtonLoading = false;
                  }else if(order.tradePayStatus === 1){
                     this.$message.error("订单已过期");
                  }else if(order.tradePayStatus ===  2){
                    this.$message.success("支付成功")
                    location.reload();
                  }else{
                    this.$message.error("订单失效，请重新创建订单进行交易")
                  }
                } else {
                  done();
                }
              },
            }).then((action) => {
              this.$message({
                type: "success",
                message: "恭喜交易成功",
              });
            });
          } else {
            alert(
              `${config.baseURL}${payApi}?orderNo=${orderNo}&return_url=${return_url}&notify_url=${notify_url}`
            );
            location.href = `${config.baseURL}${payApi}?orderNo=${orderNo}&return_url=${return_url}&notify_url=${notify_url}`;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    async remoteMethod(studentNo) {
      // 执行搜索操作
      this.students = (await useFindStudentByStudentNo(studentNo)).data.student;
    },
  },
};
</script>

<style lang="scss">
.el-message-box__message {
  height: 163px !important;
}
</style>
